/*eslint strict:0*/
/*global CasperError, console, phantom, require*/

var links = [];
var casper = require('casper').create({
    logLevel: 'info',              // Only 'info' level messages will be logged
    verbose: true                  // log messages will be printed out to the console
});

function getLinks() {
    var arr = document.querySelectorAll('h3.t a');
    return Array.prototype.map.call(arr, function(e) {
        return e.getAttribute('href');
    });
}

casper.start('https://www.baidu.com/', function() {
    // Wait for the page to be loaded
    this.waitForSelector('form[action="/s"]');
});

casper.then(function() {
    // search for 'casperjs' from baidu form
    this.fill('form[action="/s"]', { wd: 'casperjs' });
    this.click('#su');
    this.waitForSelector('#content_left');
});

casper.then(function() {
//    this.capture(new Date().getTime() + '.png');
    // aggregate results for the 'casperjs' search
    // evaluate调用的方法里面，只能编写浏览器相关的的代码，不能编写CasperJS相关的代码
    links = this.evaluate(getLinks);
});

casper.run(function() {
    // echo results in some pretty fashion
    this.echo(links.length + ' links found:');
    this.echo(' - ' + links.join('\n - '));
    this.exit();
});
